﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Xml;
using System.Linq;
//using System.Xml.Linq;
using System.Diagnostics;
using System.Text.RegularExpressions;


namespace CommonUtils
{
	public class CompressUtils
	{
		private static int s_nBuffSize = 1024 * 32;
		public static byte[] CompressGZip(byte[] arrbyteSource)
		{
			if (arrbyteSource == null) return null;
			return CompressGZip(arrbyteSource, 0, arrbyteSource.Length);
		}
		public static byte[] CompressGZip(byte[] arrbyteSource, int nIdx)
		{
			if (arrbyteSource == null) return null;
			return CompressGZip(arrbyteSource, nIdx, arrbyteSource.Length - nIdx);
		}
		public static byte[] CompressGZip(byte[] arrbyteSource, int nIdx, int nCount)
		{
			// Init:
			if (arrbyteSource == null) return null;
			byte[] arrbyteDestination = null;

			// Process:
			using (System.IO.MemoryStream msDestination = new System.IO.MemoryStream(s_nBuffSize))
			{
				using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(msDestination, System.IO.Compression.CompressionMode.Compress))
				{
					gzip.Write(arrbyteSource, nIdx, nCount);
				}
				arrbyteDestination = msDestination.ToArray();
			}

			// Return Good:
			return arrbyteDestination;
		}
		public static byte[] DecompressGZip(byte[] arrbyteSource)
		{
			if (arrbyteSource == null) return null;
			return DecompressGZip(arrbyteSource, 0, arrbyteSource.Length);
		}
		public static byte[] DecompressGZip(byte[] arrbyteSource, int nIdx)
		{
			if (arrbyteSource == null) return null;
			return DecompressGZip(arrbyteSource, nIdx, arrbyteSource.Length - nIdx);
		}
		public static byte[] DecompressGZip(byte[] arrbyteSource, int nIdx, int nCount)
		{
			// Init:
			if (arrbyteSource == null) return null;
			byte[] arrbyteDestination = null;

			// Process:
			byte[] arrbyteResult = new byte[s_nBuffSize];
			using (System.IO.MemoryStream msSource = new System.IO.MemoryStream(arrbyteSource, nIdx, nCount))
			{
				using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(msSource, System.IO.Compression.CompressionMode.Decompress))
				{
					using (System.IO.MemoryStream msDestination = new System.IO.MemoryStream(s_nBuffSize))
					{
						int nResult = 0;
						while ((nResult = gzip.Read(arrbyteResult, 0, s_nBuffSize)) > 0) // Dump Decompressed data into arrbyteResult.
						{
							msDestination.Write(arrbyteResult, 0, nResult); // Write arrbyteResult to msDestination.
						}
						arrbyteDestination = msDestination.ToArray();
					}
				}
			}

			// Return Good:
			return arrbyteDestination;
		}
	}
}
